import logging
import sys
import os


class LimitedFileHandler(logging.FileHandler):
    """
    自定义文件日志处理器，限制日志文件最大行数
    每写入 check_interval 次后检查一次行数
    """

    def __init__(self, filename, max_lines=10000, encoding='utf-8', mode='a', check_interval=500):  # 提高到500
        self.max_lines = max_lines
        self.filename = filename
        self.check_interval = check_interval
        self.write_count = 0
        super().__init__(filename, mode, encoding)

    def emit(self, record):
        """重写 emit 方法"""
        try:
            # 写入新日志
            super().emit(record)

            # 每写入 check_interval 次检查一次
            self.write_count += 1
            if self.write_count >= self.check_interval:
                self.write_count = 0
                self._cleanup_if_needed()
        except Exception:
            self.handleError(record)

    def _cleanup_if_needed(self):
        """如果日志行数超过限制，删除最老的记录"""
        try:
            if not os.path.exists(self.filename):
                return

            # 快速计数行数 - 使用errors='replace'容错处理编码问题
            with open(self.filename, 'r', encoding='utf-8', errors='replace') as f:
                line_count = sum(1 for _ in f)

            # 只有超过限制时才读取和重写
            if line_count > self.max_lines:
                with open(self.filename, 'r', encoding='utf-8', errors='replace') as f:
                    lines = f.readlines()

                # 保留最后 max_lines 行
                lines_to_keep = lines[-self.max_lines:]

                with open(self.filename, 'w', encoding='utf-8') as f:
                    f.writelines(lines_to_keep)

                deleted_count = line_count - self.max_lines
                # 使用标准日志记录清理信息
                cleanup_msg = f"日志自动清理: 删除了 {deleted_count} 条旧记录，当前保留 {self.max_lines} 条"
                print(cleanup_msg)
        except Exception as e:
            print(f"日志清理失败: {e}")


def setup_logging():
    # 生产环境：只输出WARNING及以上级别到控制台
    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setLevel(logging.WARNING)  # 提高到WARNING减少输出
    # 强制stdout使用UTF-8编码
    if hasattr(sys.stdout, 'reconfigure'):
        sys.stdout.reconfigure(encoding='utf-8')

    # 使用自定义的文件处理器
    # max_lines=10000: 最多保留 10000 行
    # check_interval=500: 每写入 500 次检查一次（提高性能）
    file_handler = LimitedFileHandler(
        "app.log",
        max_lines=10000,
        encoding='utf-8',
        check_interval=500  # 减少检查频率
    )
    file_handler.setLevel(logging.INFO)

    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    stream_handler.setFormatter(formatter)
    file_handler.setFormatter(formatter)

    logging.basicConfig(
        level=logging.INFO,
        handlers=[
            stream_handler,  # 控制台输出（UTF-8） - 只输出WARNING
            file_handler  # 日志输出到文件（UTF-8），最多10000行
        ]
    )

    # 获取 logger
    logger = logging.getLogger("ecg_auth_demo")
    return logger